import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.table.DefaultTableModel;

public class Main extends JFrame {

    // 管理所有项目和用户
    private List<Project> projects = new ArrayList<>();
    private Map<String, User> userMap = new HashMap<>();

    // 组件
    private JTabbedPane tabPane;

    // 发布项目相关
    private JTextField tfProjectId, tfProjectName, tfRule, tfStartTime, tfEndTime, tfLocation;
    private JButton btnPublish;

    // 报名相关
    private JTextField tfUserId, tfUserName;
    private JComboBox<String> cbUserType, cbEnrollType, cbProjectEnroll;
    private JButton btnEnroll;
    private JTextArea taEnrollInfo;

    // 排名相关
    private JComboBox<String> cbProjectRank;
    private JButton btnShowRank;
    private JTextArea taRankInfo;

    // 裁判评分相关
    private JComboBox<String> cbJudgeProject;
    private JComboBox<String> cbJudgeParticipant;
    private JTextField tfScore;
    private JButton btnSubmitScore;
    private JTextArea taJudgeInfo;

    public Main() {
        setTitle("河南工业大学运动会管理系统");
        setSize(900, 650);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 顶部Logo
        JPanel topPanel = new JPanel();
        topPanel.setBackground(new Color(255, 182, 193));
        JLabel lblLogo = new JLabel("🏅 河南工业大学运动会管理系统");
        lblLogo.setFont(new Font("微软雅黑", Font.BOLD, 26));
        lblLogo.setForeground(Color.WHITE);
        topPanel.add(lblLogo);
        add(topPanel, BorderLayout.NORTH);

        tabPane = new JTabbedPane();
        add(tabPane, BorderLayout.CENTER);

        initPublishPanel();
        initEnrollPanel();
        initRankingPanel();
        initJudgeScorePanel();

        
    }



    // ---------- 初始化 发布项目 面板 ----------
    private void initPublishPanel() {
        JPanel panelPublish = new JPanel(new GridBagLayout());
        panelPublish.setBackground(new Color(255, 228, 225));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 12, 10, 12);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        String[] labels = {"项目ID:", "项目名称:", "规则:", "开始时间(yyyy-MM-dd HH:mm):", "结束时间(yyyy-MM-dd HH:mm):", "地点:"};
        JTextField[] inputs = new JTextField[6];
        tfProjectId = new JTextField(15);
        tfProjectName = new JTextField(15);
        tfRule = new JTextField(15);
        tfStartTime = new JTextField(15);
        tfEndTime = new JTextField(15);
        tfLocation = new JTextField(15);
        inputs[0] = tfProjectId;
        inputs[1] = tfProjectName;
        inputs[2] = tfRule;
        inputs[3] = tfStartTime;
        inputs[4] = tfEndTime;
        inputs[5] = tfLocation;

        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.EAST;
            JLabel lbl = new JLabel(labels[i]);
            lbl.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            panelPublish.add(lbl, gbc);

            gbc.gridx = 1;
            gbc.anchor = GridBagConstraints.WEST;
            inputs[i].setFont(new Font("微软雅黑", Font.PLAIN, 14));
            panelPublish.add(inputs[i], gbc);
        }

        gbc.gridx = 0;
        gbc.gridy = labels.length;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        btnPublish = new JButton("发布项目");
        btnPublish.setFont(new Font("微软雅黑", Font.BOLD, 16));
        btnPublish.setBackground(new Color(255, 182, 193));
        panelPublish.add(btnPublish, gbc);

        btnPublish.addActionListener(e -> publishProject());

        tabPane.addTab("管理者发布项目", panelPublish);
    }

    private void publishProject() {
        String id = tfProjectId.getText().trim();
        String name = tfProjectName.getText().trim();
        String rule = tfRule.getText().trim();
        String start = tfStartTime.getText().trim();
        String end = tfEndTime.getText().trim();
        String location = tfLocation.getText().trim();

        if (id.isEmpty() || name.isEmpty() || rule.isEmpty() || start.isEmpty() || end.isEmpty() || location.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写完整项目信息！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date startTime = sdf.parse(start);
            Date endTime = sdf.parse(end);

            Project p = new Project(id, name, rule, startTime, endTime, location);
            projects.add(p);

            JOptionPane.showMessageDialog(this, "项目发布成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            clearPublishForm();


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "时间格式错误，请使用 yyyy-MM-dd HH:mm 格式", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void clearPublishForm() {
        tfProjectId.setText("");
        tfProjectName.setText("");
        tfRule.setText("");
        tfStartTime.setText("");
        tfEndTime.setText("");
        tfLocation.setText("");
    }

    // ---------- 初始化 报名 面板 ----------
    private void initEnrollPanel() {
        JPanel panelEnroll = new JPanel(new GridBagLayout());
        panelEnroll.setBackground(new Color(255, 228, 225));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 15, 10, 15);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel lblUserId = new JLabel("用户ID:");
        JLabel lblUserName = new JLabel("姓名:");
        JLabel lblUserType = new JLabel("身份:");
        JLabel lblEnrollType = new JLabel("报名类型:");
        JLabel lblProject = new JLabel("选择项目:");

        tfUserId = new JTextField(15);
        tfUserName = new JTextField(15);
        cbUserType = new JComboBox<>(new String[]{"学生", "老师"});
        cbEnrollType = new JComboBox<>(new String[]{"参赛", "裁判员", "志愿者"});
        cbProjectEnroll = new JComboBox<>();

        // 左右对称排布
        gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.EAST;
        panelEnroll.add(lblUserId, gbc);
        gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
        panelEnroll.add(tfUserId, gbc);

        gbc.gridx = 0; gbc.gridy = 1; gbc.anchor = GridBagConstraints.EAST;
        panelEnroll.add(lblUserName, gbc);
        gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
        panelEnroll.add(tfUserName, gbc);

        gbc.gridx = 0; gbc.gridy = 2; gbc.anchor = GridBagConstraints.EAST;
        panelEnroll.add(lblUserType, gbc);
        gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
        panelEnroll.add(cbUserType, gbc);

        gbc.gridx = 0; gbc.gridy = 3; gbc.anchor = GridBagConstraints.EAST;
        panelEnroll.add(lblEnrollType, gbc);
        gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
        panelEnroll.add(cbEnrollType, gbc);

        gbc.gridx = 0; gbc.gridy = 4; gbc.anchor = GridBagConstraints.EAST;
        panelEnroll.add(lblProject, gbc);
        gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
        panelEnroll.add(cbProjectEnroll, gbc);

        gbc.gridx = 0; gbc.gridy = 5; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.CENTER;
        btnEnroll = new JButton("报名");
        btnEnroll.setFont(new Font("微软雅黑", Font.BOLD, 16));
        btnEnroll.setBackground(new Color(255, 182, 193));
        panelEnroll.add(btnEnroll, gbc);

        taEnrollInfo = new JTextArea(8, 50);
        taEnrollInfo.setEditable(false);
        taEnrollInfo.setLineWrap(true);
        taEnrollInfo.setWrapStyleWord(true);
        taEnrollInfo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JScrollPane scrollPane = new JScrollPane(taEnrollInfo);

        gbc.gridy = 6; gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH;
        panelEnroll.add(scrollPane, gbc);

        btnEnroll.addActionListener(e -> enrollUser());

        tabPane.addTab("报名系统", panelEnroll);
    }

    private void enrollUser() {
        String id = tfUserId.getText().trim();
        String name = tfUserName.getText().trim();
        String userTypeStr = (String) cbUserType.getSelectedItem();
        String enrollTypeStr = (String) cbEnrollType.getSelectedItem();
        String projectName = (String) cbProjectEnroll.getSelectedItem();

        if (id.isEmpty() || name.isEmpty() || projectName == null) {
            JOptionPane.showMessageDialog(this, "请完整填写报名信息！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        User user = userMap.get(id);
        if (user == null) {
            user = new User(id, name, userTypeStr.equals("学生") ? UserType.STUDENT : UserType.TEACHER);
            userMap.put(id, user);
        }

        Project project = findProjectByName(projectName);
        if (project == null) {
            JOptionPane.showMessageDialog(this, "项目不存在！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        switch (enrollTypeStr) {
            case "参赛":
                project.addParticipant(user);
                break;
            case "裁判员":
                project.addJudge(user);
                break;
            case "志愿者":
                project.addVolunteer(user);
                break;
        }

        taEnrollInfo.append(String.format("用户[%s - %s] 报名 [%s] 类型 [%s]\n", id, name, projectName, enrollTypeStr));
        tfUserId.setText("");
        tfUserName.setText("");
    }

    private Project findProjectByName(String name) {
        for (Project p : projects) {
            if (p.name.equals(name)) return p;
        }
        return null;
    }


    private void clearEnrollForm() {
        tfUserId.setText("");
        tfUserName.setText("");
        cbUserType.setSelectedIndex(0);
        cbEnrollType.setSelectedIndex(0);
        if (cbProjectEnroll.getItemCount() > 0) cbProjectEnroll.setSelectedIndex(0);
    }



    // ---------- 初始化 排名 面板 ----------
    private void initRankingPanel() {

        JPanel panelRank = new JPanel(new BorderLayout());
        panelRank.setBackground(new Color(255, 228, 225));

        JPanel top = new JPanel();
        top.setBackground(new Color(255, 182, 193));
        JLabel lbl = new JLabel("选择项目查看排名:");
        lbl.setFont(new Font("微软雅黑", Font.BOLD, 16));
        cbProjectRank = new JComboBox<>();
        btnShowRank = new JButton("显示排名");
        btnShowRank.setBackground(new Color(255, 182, 193));
        btnShowRank.setFont(new Font("微软雅黑", Font.BOLD, 16));
        top.add(lbl);
        top.add(cbProjectRank);
        top.add(btnShowRank);

        taRankInfo = new JTextArea();
        taRankInfo.setEditable(false);
        taRankInfo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        taRankInfo.setLineWrap(true);
        taRankInfo.setWrapStyleWord(true);
        JScrollPane sp = new JScrollPane(taRankInfo);

        panelRank.add(top, BorderLayout.NORTH);
        panelRank.add(sp, BorderLayout.CENTER);

        btnShowRank.addActionListener(e -> showRanking());

        tabPane.addTab("排名查询", panelRank);
    }

    private void showRanking() {
        String projectName = (String) cbProjectRank.getSelectedItem();
        if (projectName == null) {
            JOptionPane.showMessageDialog(this, "请选择一个项目！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Project project = findProjectByName(projectName);
        if (project == null) return;

        List<User> ranking = project.getRanking();
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("项目[%s] 排名:\n", projectName));
        int rank = 1;
        for (User u : ranking) {
            sb.append(String.format("%d. %s (%s) - 得分: %d\n", rank++, u.name, u.id, project.getScore(u)));
        }

        taRankInfo.setText(sb.toString());
    }

//评分面板
private void initJudgeScorePanel() {
    JPanel panelJudge = new JPanel(new GridBagLayout());
    panelJudge.setBackground(new Color(255, 228, 225));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(10, 15, 10, 15);
    gbc.fill = GridBagConstraints.HORIZONTAL;

    Map<String, Map<String, Integer>> scores = new HashMap<>();

    JLabel lblProject = new JLabel("选择项目:");
    JLabel lblParticipant = new JLabel("选择选手:");
    JLabel lblScore = new JLabel("评分（0-100）:");

    // 这里去掉JComboBox等的局部变量声明，使用成员变量
    cbJudgeParticipant = new JComboBox<>();
    tfScore = new JTextField(5);
    btnSubmitScore = new JButton("提交评分");
    taJudgeInfo = new JTextArea(8, 50);
    taJudgeInfo.setEditable(false);
    taJudgeInfo.setLineWrap(true);
    taJudgeInfo.setWrapStyleWord(true);
    taJudgeInfo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    JScrollPane scrollPane = new JScrollPane(taJudgeInfo);

    // 载入项目到cbJudgeProject
    cbJudgeProject.removeAllItems();
    for (Project p : projects) {
        cbJudgeProject.addItem(p.name);
    }

    // 选中项目后刷新参赛选手列表
    cbJudgeProject.addActionListener(e -> {
        String selectedProject = (String) cbJudgeProject.getSelectedItem();
        cbJudgeParticipant.removeAllItems();
        if (selectedProject != null) {
            Project project = findProjectByName(selectedProject);
            if (project != null) {
                for (User u : project.getParticipants()) {
                    cbJudgeParticipant.addItem(u.getId() + " - " + u.getName());
                }
            }
        }
    });

    gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.EAST;
    panelJudge.add(lblProject, gbc);
    gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
    panelJudge.add(cbJudgeProject, gbc);

    gbc.gridx = 0; gbc.gridy = 1; gbc.anchor = GridBagConstraints.EAST;
    panelJudge.add(lblParticipant, gbc);
    gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
    panelJudge.add(cbJudgeParticipant, gbc);

    gbc.gridx = 0; gbc.gridy = 2; gbc.anchor = GridBagConstraints.EAST;
    panelJudge.add(lblScore, gbc);
    gbc.gridx = 1; gbc.anchor = GridBagConstraints.WEST;
    panelJudge.add(tfScore, gbc);

    gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.CENTER;
    panelJudge.add(btnSubmitScore, gbc);

    gbc.gridx = 0; gbc.gridy = 4; gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH;
    panelJudge.add(scrollPane, gbc);

    btnSubmitScore.addActionListener(e -> {
        String projectName = (String) cbJudgeProject.getSelectedItem();
        String participantInfo = (String) cbJudgeParticipant.getSelectedItem();
        String scoreText = tfScore.getText().trim();

        if (projectName == null || participantInfo == null || scoreText.isEmpty()) {
            JOptionPane.showMessageDialog(panelJudge, "请完整选择项目、选手并填写评分！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int score;
        try {
            score = Integer.parseInt(scoreText);
            if (score < 0 || score > 100) throw new NumberFormatException();
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(panelJudge, "评分必须是0-100的整数！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String userId = participantInfo.split(" - ")[0];
        scores.putIfAbsent(projectName, new HashMap<>());
        scores.get(projectName).put(userId, score);

        taJudgeInfo.append(String.format("项目[%s] 选手[%s] 得分: %d\n", projectName, participantInfo, score));
        tfScore.setText("");
    });

    if (cbJudgeProject.getItemCount() > 0) {
        cbJudgeProject.setSelectedIndex(0);
    }

    tabPane.addTab("裁判评分", panelJudge);
}


    public static void main(String[] args) {
        // 设置粉色主题
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            UIManager.put("control", new Color(255, 228, 225));
            UIManager.put("nimbusBase", new Color(255, 182, 193));
            UIManager.put("nimbusBlueGrey", new Color(255, 192, 203));
            UIManager.put("nimbusFocus", new Color(255, 182, 193));
        } catch (Exception e) {
            // 忽略异常
        }

        SwingUtilities.invokeLater(() -> {
            Main frame = new Main();
            frame.setVisible(true);
        });
    }

    // --------- 辅助类 ---------
    enum UserType { STUDENT, TEACHER }

    enum EnrollType {
        PARTICIPANT("参赛"),
        REFEREE("裁判员"),
        VOLUNTEER("志愿者");

        private final String text;
        EnrollType(String t) { text = t; }
        public static EnrollType fromString(String s) {
            for (EnrollType e : values()) if (e.text.equals(s)) return e;
            return PARTICIPANT;
        }
        @Override public String toString() { return text; }
    }

    static class User {
        String id, name;
        UserType type;

        public User(String id, String name, UserType type) {
            this.id = id;
            this.name = name;
            this.type = type;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof User)) return false;
            User u = (User) o;
            return Objects.equals(id, u.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }


    }

    static class Score {
        User referee;
        int value;

        public Score(User referee, int value) {
            this.referee = referee;
            this.value = value;
        }
    }

    static class Project {
        String id, name, rule, location;
        Date startTime, endTime;
        List<User> judges = new ArrayList<>();
        List<User> participants = new ArrayList<>();
        List<User> referees = new ArrayList<>();
        List<User> volunteers = new ArrayList<>();

        Map<User, List<Score>> scoreMap = new HashMap<>();
        Map<String, Integer> scores = new HashMap<>();
        Map<String, Integer> userScores = new HashMap<>();
        public Project(String id, String name, String rule, Date startTime, Date endTime, String location) {
            this.id = id;
            this.name = name;
            this.rule = rule;
            this.startTime = startTime;
            this.endTime = endTime;
            this.location = location;
        }


        // 设置某个用户的评分
        public void setScore(User user, int score) {
            userScores.put(user.getId(), score);
        }
        public int getScore(User user) {
            return scores.getOrDefault(user.getId(), 0);
        }

        public void addJudge(User user) {
            if (!judges.contains(user)) judges.add(user);
        }

        public void addParticipant(User u) {
            if (!participants.contains(u)) participants.add(u);
        }

        public void addReferee(User u) {
            if (!referees.contains(u)) referees.add(u);
        }

        public void addVolunteer(User u) {
            if (!volunteers.contains(u)) volunteers.add(u);
        }

        public boolean addScore(User referee, User participant, int value) {
            if (!referees.contains(referee) || !participants.contains(participant)) return false;
            scoreMap.putIfAbsent(participant, new ArrayList<>());
            scoreMap.get(participant).add(new Score(referee, value));
            return true;
        }

        public int getTotalScore(User participant) {
            if (!scoreMap.containsKey(participant)) return 0;
            return scoreMap.get(participant).stream().mapToInt(s -> s.value).sum();
        }

        public List<User> getRanking() {
            return participants.stream()
                    .sorted((a, b) -> Integer.compare(getTotalScore(b), getTotalScore(a)))
                    .collect(Collectors.toList());
        }
        public List<User> getParticipants() {
            return participants;
        }
    }
    private String getProjectName(String projectId) {
        for (Project p : projects) {
            if (p.id.equals(projectId)) return p.name;
        }
        return "";
    }
    public class Enrollment {
        private String studentId;
        private String name;
        private String projectId;
        private EnrollType type;
        private int score;

        // 构造函数，初始score设为-1表示未评分
        public Enrollment(String studentId, String name, String projectId, EnrollType type) {
            this.studentId = studentId;
            this.name = name;
            this.projectId = projectId;
            this.type = type;
            this.score = -1;
        }

        // getter 和 setter 方法
        public String getStudentId() {
            return studentId;
        }

        public void setStudentId(String studentId) {
            this.studentId = studentId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getProjectId() {
            return projectId;
        }

        public void setProjectId(String projectId) {
            this.projectId = projectId;
        }

        public EnrollType getType() {
            return type;
        }

        public void setType(EnrollType type) {
            this.type = type;
        }

        public int getScore() {
            return score;
        }

        public void setScore(int score) {
            this.score = score;
        }

    }

    private JPanel createJudgeScorePanel() {
        List<Enrollment> enrollments = new ArrayList<>();

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("裁判打分"));

        JPanel top = new JPanel(new FlowLayout());
        JComboBox<String> cbProjectJudge = new JComboBox<>();
        JButton btnLoadParticipants = new JButton("加载选手");

        top.add(new JLabel("选择项目："));
        top.add(cbProjectJudge);
        top.add(btnLoadParticipants);

        DefaultTableModel model = new DefaultTableModel(new String[]{"学号", "姓名", "得分"}, 0);
        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);

        JButton btnSubmitScores = new JButton("提交打分");

        panel.add(top, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(btnSubmitScores, BorderLayout.SOUTH);

        // 加载下拉框
        for (Project p : projects) {
            cbProjectJudge.addItem(p.name);
        }

        // 加载选手按钮事件
        btnLoadParticipants.addActionListener(e -> {
            model.setRowCount(0);
            String selectedProject = cbProjectJudge.getSelectedItem().toString();
            for (Enrollment en : enrollments) {
                if (getProjectName(en.projectId).equals(selectedProject)
                        && en.type == EnrollType.PARTICIPANT) {
                    model.addRow(new Object[]{en.studentId, en.name, en.score == -1 ? "" : en.score});
                }
            }
        });

        // 提交打分
        btnSubmitScores.addActionListener(e -> {
            for (int i = 0; i < model.getRowCount(); i++) {
                String id = model.getValueAt(i, 0).toString();
                int score;
                try {
                    score = Integer.parseInt(model.getValueAt(i, 2).toString());
                    if (score < 0 || score > 100) throw new NumberFormatException();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(panel, "第 " + (i + 1) + " 行的得分无效！应为0-100整数");
                    return;
                }
                for (Enrollment en : enrollments) {
                    if (en.studentId.equals(id)) {
                        en.score = score;
                        break;
                    }
                }
            }
            JOptionPane.showMessageDialog(panel, "成绩已提交！");
        });

        return panel;
    }
    private JPanel createVolunteerPanel() {
     List<Enrollment> enrollments = new ArrayList<>();

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("志愿者任务分配"));

        JPanel top = new JPanel(new FlowLayout());
        JComboBox<String> cbVolProject = new JComboBox<>();
        JComboBox<String> cbVolunteer = new JComboBox<>();
        JButton btnAssign = new JButton("分配任务");

        top.add(new JLabel("选择项目："));
        top.add(cbVolProject);
        top.add(new JLabel("选择志愿者："));
        top.add(cbVolunteer);
        top.add(btnAssign);

        JTextArea taTasks = new JTextArea(10, 40);
        taTasks.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(taTasks);

        panel.add(top, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 加载下拉数据
        for (Project p : projects) cbVolProject.addItem(p.name);
        for (Enrollment e : enrollments) {
            if (e.type == EnrollType.VOLUNTEER) cbVolunteer.addItem(e.name + "(" + e.studentId + ")");
        }

        btnAssign.addActionListener(e -> {
            String proj = cbVolProject.getSelectedItem().toString();
            String volunteerStr = cbVolunteer.getSelectedItem().toString();
            String vid = volunteerStr.substring(volunteerStr.indexOf("(") + 1, volunteerStr.indexOf(")"));

            taTasks.append("分配给 " + volunteerStr + " 的任务：" + proj + "\n");
        });

        return panel;
    }

}
